package com.qiaofang.service.impl;

import com.qiaofang.common.constant.ExceptionEnum;
import com.qiaofang.common.exception.BusinessException;
import com.qiaofang.common.utils.Token;
import com.qiaofang.common.utils.DateUtil;
import com.qiaofang.common.utils.PasswordUtil;
import com.qiaofang.common.utils.StringUtil;
import com.qiaofang.common.utils.TokenUtil;
import com.qiaofang.dto.LoginDTO;
import com.qiaofang.entity.User;
import com.qiaofang.repository.UserRepository;
import com.qiaofang.service.UserService;
import com.qiaofang.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public LoginVO login(LoginDTO dto) {
        LoginVO vo = new LoginVO();
        User user = userRepository.getUserByAccount(dto.getUserAccount());
        if (user != null) {
            if (StringUtil.equals(PasswordUtil.md5Hex(dto.getUserPwd()), user.getUserPwd())) {
                Token token = new Token(user.getId(), user.getUserUuid(), DateUtil.getCurrentTime(), UUID.randomUUID().toString());
                vo.setToken(token.toString());
                TokenUtil.addToken(token.toString(), token);
            } else {
                throw new BusinessException(ExceptionEnum.ACCOUNT_PWD_WRONG);
            }
        } else {
            throw new BusinessException(ExceptionEnum.NOT_EXIST_ACCOUNT);
        }
        return vo;
    }
}
